import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';

jsOpenCameraOrImage(
  ImageSource source,
  Function(String path) onSelected, {
  required Function() onCameraAccessDenied,
  required Function() onPhotoAccessDenied,
}) async {
  try {
    final picker = ImagePicker();
    final xFile = await picker.pickImage(source: source);
    debugPrint("[camare] path=${xFile?.path}");
    onSelected(xFile?.path ?? "");
  } catch (e) {
    if (e is PlatformException) {
      if ("camera_access_denied" == e.code) {
        onCameraAccessDenied();
      } else if ("photo_access_denied" == e.code) {
        onPhotoAccessDenied();
      }
    }
    debugPrint("[camare] e=$e");
    return null;
  }
}

Future<String> jsOpenCropImage(String? path) async {
  if (path == null || path.isEmpty) return "";

  CroppedFile? croppedImage = await ImageCropper().cropImage(
    sourcePath: path,
    aspectRatio: const CropAspectRatio(ratioX: 1, ratioY: 1), //裁剪框比例
    uiSettings: [
      AndroidUiSettings(toolbarTitle: 'Crop', lockAspectRatio: true //锁定图片纵横比
          ),
      IOSUiSettings(
        title: 'Crop',
        resetButtonHidden: true, //不显示重置按钮
        aspectRatioLockEnabled: true, //锁定图片纵横比
        aspectRatioPickerButtonHidden: true, //隐藏切换纵横比按钮
        doneButtonTitle: "Yes",
        cancelButtonTitle: "Cancel",
      )
    ],
  );

  if (croppedImage != null) {
    return croppedImage.path;
  } else {
    return "";
  }
}
